import 'package:flutter_demo/http/product.dart';
import 'package:flutter_demo/models/request/product.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import '../../models/product_model/product_model.dart';

class Goods_product_listLogic extends GetxController {

  /// 是否推荐商品
  bool featured = false;


  //刷新的控制器
  final RefreshController  refreshController = RefreshController(initialRefresh: true);

  // 页码
  int _page = 1;

  // 页尺寸
  final int _limit = 20;

  //数据list集合
  List<ProductModel> items = [];

  ///请求网络数据
  Future<bool> _loadSearch(bool isRefresh) async{
     print("featured${featured}");
     var result = await ProductApi.products(ProductsReq(
       page: isRefresh ? 1 : _page,
       prePage: _limit,
       featured: featured
     ));

     //下拉数据
     if(isRefresh){
       _page = 1;
       items.clear();
     }

     if(result.isNotEmpty){
       _page ++;
       items.addAll(result);
     }

     return result.isEmpty;
  }

  ///上拉加载更多
  void onLoading() async {
    if (items.isNotEmpty) {
      try {
        // 拉取数据是否为空
        var isEmpty = await _loadSearch(false);

        if (isEmpty) {
          // 设置无数据
          refreshController.loadNoData();
        } else {
          // 加载完成
          refreshController.loadComplete();
        }
      } catch (e) {
        // 加载失败
        refreshController.loadFailed();
      }
    } else {
      // 设置无数据
      refreshController.loadNoData();
    }
    update(["goods_product_list"]);
  }


  //下拉刷新
  void onRefresh() async{
    try{
      await _loadSearch(true);
      refreshController.refreshCompleted();
    }catch(error){
      refreshController.refreshFailed();
    }
    update(["goods_product_list"]);
  }

  @override
  void onInit() {
    super.onInit();
    /// 是否推荐商品,true 是推荐商品，false是最新商品
    featured = Get.arguments["featured"] ?? false;
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  @override
  void onClose() {
    super.onClose();
    refreshController.dispose();
  }


  _initData() {
    update(["goods_product_list"]);
  }
}
